<template>
  <div class="user-management">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <div class="search-inputs">
        <el-input
          v-model="searchForm.account"
          placeholder="请输入账户"
          clearable
          @clear="handleSearch"
        ></el-input>
        <el-input
          v-model="searchForm.name"
          placeholder="请输入姓名"
          clearable
          @clear="handleSearch"
        ></el-input>
        <el-input
          v-model="searchForm.phone"
          placeholder="全手机号或手机号后四位"
          clearable
          @clear="handleSearch"
        ></el-input>
        <el-select v-model="searchForm.status" placeholder="请选择状态" clearable @change="handleSearch">
          <el-option label="正常" value="0"></el-option>
          <el-option label="未激活" value="1"></el-option>
          <el-option label="冻结" value="2"></el-option>
        </el-select>
        <el-select v-model="searchForm.gender" placeholder="请选择性别" clearable @change="handleSearch">
          <el-option label="男" value="male"></el-option>
          <el-option label="女" value="female"></el-option>
        </el-select>
      </div>
      <div>
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增用户</el-button>
        <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetSearch">重置</el-button>
      </div>
    </div>

    <!-- 表格操作栏 -->
    <div class="table-actions">
      <el-button @click="exportData" icon="el-icon-download">导出数据</el-button>
      <el-button @click="batchDelete" :disabled="selectedUsers.length === 0" icon="el-icon-delete">批量删除</el-button>
    </div>

    <!-- 用户数据表格 -->
    <div class="table-container">
      <el-table
        :data="tableData"
        stripe
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column prop="id" label="ID" width="180"></el-table-column>
        <el-table-column prop="account" label="账户" width="180"></el-table-column>
        <el-table-column prop="name" label="姓名" width="100"></el-table-column>
        <el-table-column prop="nickname" label="昵称" width="180"></el-table-column>
        <el-table-column prop="phone" label="电话" width="120"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="180">
          <template slot-scope="scope">
            <span class="text-truncate">{{ scope.row.email }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="注册日期" width="160" sortable></el-table-column>
        <el-table-column prop="birth" label="出生日期" width="120"></el-table-column>
        <el-table-column prop="avatar" label="头像" width="80">
          <template slot-scope="scope">
            <div class="avatar-container">
              <img
                :src="scope.row.avatar || defaultAvatar"
                alt="用户头像"
                class="avatar-img"
              >
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="gender" label="性别" width="80">
          <template slot-scope="scope">
            <span>{{ formatGender(scope.row.gender) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="introduction" label="简介" min-width="150">
          <template slot-scope="scope">
            <span v-if="scope.row.introduction && scope.row.introduction.length > 10" class="text-truncate">
              {{ scope.row.introduction }}
            </span>
            <span v-else>{{ scope.row.introduction || '-' }}</span>
            <el-button
              v-if="scope.row.introduction && scope.row.introduction.length > 10"
              type="text"
              size="mini"
              @click="showDetail('简介', scope.row.introduction)"
            >查看详情
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="motto" label="格言" min-width="150">
          <template slot-scope="scope">
            <span v-if="scope.row.motto && scope.row.motto.length > 10" class="text-truncate">
              {{ scope.row.motto }}
            </span>
            <span v-else>{{ scope.row.motto || '-' }}</span>
            <el-button
              v-if="scope.row.motto && scope.row.motto.length > 10"
              type="text"
              @click="showDetail('格言', scope.row.motto)"
            >查看详情
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="地址" min-width="150">
          <template slot-scope="scope">
            <span v-if="scope.row.address && scope.row.address.length > 10" class="text-truncate">
              {{ scope.row.address }}
            </span>
            <span v-else>{{ scope.row.address || '-' }}</span>
            <el-button
              v-if="scope.row.address && scope.row.address.length > 10"
              type="text"
              @click="showDetail('地址', scope.row.address)"
            >查看详情
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <span :class="getStatusClass(scope.row.status, scope.row.deleted)">
              {{ formatStatus(scope.row.status, scope.row.deleted) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="distinguish_mark" label="系统区分标识" width="150"></el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template slot-scope="scope">
            <div class="operation-buttons">
              <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button size="mini" type="warning" @click="handleResetPassword(scope.row)">重置密码</el-button>
              <el-button
                size="mini"
                :type="scope.row.deleted ? 'success' : 'danger'"
                @click="handleDelete(scope.row)"
              >{{ scope.row.deleted ? '恢复' : '删除' }}
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="page">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.pageNum"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total"
      ></el-pagination>
    </div>

    <!-- 详情弹窗 -->
    <el-dialog
      :title="detailTitle"
      :visible.sync="detailDialogVisible"
      width="50%"
    >
      <div class="detail-content">{{ detailContent }}</div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>

    <!-- 重置密码弹窗 -->
    <el-dialog
      title="重置密码"
      :visible.sync="resetPasswordDialogVisible"
      width="30%"
    >
      <el-form :model="resetPasswordForm" label-width="100px">
        <el-form-item label="新密码">
          <el-input v-model="resetPasswordForm.newPassword" type="password" placeholder="请输入新密码"></el-input>
        </el-form-item>
        <el-form-item label="确认密码">
          <el-input v-model="resetPasswordForm.confirmPassword" type="password" placeholder="请再次输入新密码"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetPasswordDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmResetPassword">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { fetchUserPage, upPassword } from '@/api/adminSysUser'

export default {
  name: 'sysUserManagement',
  data() {
    return {
      searchForm: {
        account: '',
        name: '',
        phone: '',
        status: '',
        gender: ''
      },
      tableData: [],
      selectedUsers: [],
      loading: false,
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      detailDialogVisible: false,
      detailTitle: '',
      detailContent: '',
      resetPasswordDialogVisible: false,
      resetPasswordForm: {
        newPassword: '',
        confirmPassword: '',
        userId: null
      }
    }
  },
  mounted() {
    this.fetchUserData()
  },
  methods: {
    // 获取用户数据
    async fetchUserData() {
      this.loading = true

      const res = await fetchUserPage({
        page: this.page,
        param: {
          ...this.searchForm
        }
      })
      this.tableData = res.records || []
      this.tableData.forEach(item => {
        item.avatar = process.env.VUE_APP_BASE_HOST + item.avatar
      })
      this.page.total = res.total * 1 || 0
      this.loading = false
    },
    // 搜索用户
    handleSearch() {
      this.page.pageNum = 1
      this.fetchUserData()
    },
    // 重置搜索条件
    resetSearch() {
      this.searchForm = {
        account: '',
        name: '',
        phone: '',
        status: '',
        gender: ''
      }
      this.handleSearch()
    },
    // 显示详情弹窗
    showDetail(title, content) {
      this.detailTitle = title
      this.detailContent = content
      this.detailDialogVisible = true
    },
    // 格式化性别显示
    formatGender(gender) {
      const genderMap = {
        'male': '男',
        'female': '女'
      }
      return genderMap[gender] || '未知'
    },
    // 格式化状态显示
    formatStatus(status, deleted) {
      if (deleted === 1) return '已删除'

      const statusMap = {
        0: '正常',
        1: '未激活',
        2: '冻结'
      }
      return statusMap[status] || '未知'
    },
    // 获取状态样式类
    getStatusClass(status, deleted) {
      if (deleted === 1) return 'status-deleted'

      const classMap = {
        0: 'status-active',
        1: 'status-inactive',
        2: 'status-frozen'
      }
      return classMap[status] || ''
    },
    // 处理分页大小变化
    handleSizeChange(size) {
      this.page.pageSize = size
      this.fetchUserData()
    },
    // 处理当前页变化
    handleCurrentChange(page) {
      this.page.pageNum = page
      this.fetchUserData()
    },
    // 处理表格选择
    handleSelectionChange(selection) {
      this.selectedUsers = selection
    },
    // 新增用户
    handleAdd() {
      this.$message.info('新增用户功能待实现')
    },
    // 编辑用户
    handleEdit(user) {
      this.$message.info(`编辑用户: ${user.name}`)
    },
    // 重置密码
    handleResetPassword(user) {
      this.resetPasswordForm.userId = user.id
      this.resetPasswordForm.newPassword = ''
      this.resetPasswordForm.confirmPassword = ''
      this.resetPasswordDialogVisible = true
    },
    // 确认重置密码
    async confirmResetPassword() {
      if (!this.resetPasswordForm.newPassword) {
        this.$message.error('请输入新密码')
        return
      }

      if (this.resetPasswordForm.newPassword !== this.resetPasswordForm.confirmPassword) {
        this.$message.error('两次输入的密码不一致')
        return
      }

      // 模拟API请求
      this.loading = true

      await upPassword({
        id: this.resetPasswordForm.userId,
        password: this.resetPasswordForm.newPassword
      })

      this.$notify({ type: 'success', message: '密码重置成功' })
      this.resetPasswordDialogVisible = false
      this.loading = false
    },
    // 删除/恢复用户
    handleDelete(user) {
      const action = user.deleted ? '恢复' : '删除'
      this.$confirm(`确定要${action}用户 "${user.name}" 吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 模拟API请求
        this.loading = true
        setTimeout(() => {
          this.$message.success(`${action}用户成功`)
          this.fetchUserData()
        }, 500)
      }).catch(() => {
        this.$message.info('已取消操作')
      })
    },
    // 批量删除
    batchDelete() {
      if (this.selectedUsers.length === 0) {
        this.$message.warning('请先选择用户')
        return
      }

      const names = this.selectedUsers.map(user => user.name).join(', ')
      this.$confirm(`确定要删除选中的 ${this.selectedUsers.length} 个用户吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 模拟API请求
        this.loading = true
        setTimeout(() => {
          this.$message.success('批量删除成功')
          this.fetchUserData()
        }, 500)
      }).catch(() => {
        this.$message.info('已取消操作')
      })
    },
    // 导出数据
    exportData() {
      this.$message.info('数据导出功能待实现')
    }
  }
}
</script>

<style scoped lang="scss">
.user-management {
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

  .search-bar {
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;

    .search-inputs {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;

      .el-input, .el-select {
        width: 200px;
      }
    }
  }

  .table-actions {
    display: flex;
    justify-content: space-between;
    margin-bottom: 15px;
  }

  .table-container {
    margin-bottom: 20px;
  }

  .page {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
  }

  .text-truncate {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 150px;
    display: inline-block;
  }

  .detail-content {
    max-height: 300px;
    overflow-y: auto;
    padding: 10px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    background-color: #fafafa;
    white-space: pre-wrap;
    word-break: break-all;
  }

  .avatar-img {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    object-fit: cover;
  }

  .status-active {
    color: #67c23a;
  }

  .status-inactive {
    color: #e6a23c;
  }

  .status-frozen {
    color: #f56c6c;
  }

  .status-deleted {
    color: #909399;
  }

  .operation-buttons {
    display: flex;
  }
}
</style>
